import {login, logout, getInfo} from '@/api/login/login.js'
import { getToken, setToken, removeToken } from '@/utils/auth'
import {defineStore} from "pinia";


const useUserStore = defineStore(
    'user',
    {
        state: () => ({
            token: getToken(),
            id: '',
            name: '',
            email: '',
            avatar: '',
            roles: [],
            permissions: []
        }),
        actions: {
            // 登录
            login(userInfo) {
                return new Promise((resolve, reject) => {
                    login(userInfo).then(res => {
                        if (res.data.code === 200){
                            setToken("Bearer " + res.data.result.token)
                            this.token = "Bearer " + res.data.result.token
                        }
                        resolve(res)
                    }).catch(error => {
                        reject(error)
                    })
                })
            },
            // 获取用户信息
            getInfo() {
                return new Promise((resolve, reject) => {
                    getInfo().then(res => {
                        const user = res.data.result
                        this.id = user.userId
                        this.name = user.username
                        this.avatar = user.userPhoto
                        this.email = user.email
                        resolve(res)
                    }).catch(error => {
                        reject(error)
                    })
                })
            },

            // 退出系统
            logOut() {
                return new Promise((resolve, reject) => {
                    logout(this.token).then(res => {
                        this.token = ''
                        removeToken()
                        resolve(res)
                    }).catch(error => {
                        reject(error)
                    })
                })
            }
        },
        persist: true, // 开启持久化
    })

export default useUserStore
